<template>
  <div class="event-center-wrap">
    <el-card class="box-card">
      <div>
        <div class="clearfix">
          <span>自定义事件</span>
          <el-button class="add-event-center" type="primary" @click="addEvent">添加事件</el-button>
        </div>
        <el-table :data="lowCode.eventCollection" style="width: 100%">
          <el-table-column prop="code" label="事件编码"> </el-table-column>
          <el-table-column prop="describe" label="事件描述"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="scope">
              <el-button @click="editor(scope.row)" type="primary" size="small">编辑</el-button>
              <el-popconfirm title="你确认要删除这个?" @confirm="remove(scope.row)">
                <template #reference>
                  <el-button type="danger" size="small"> 删除 </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-dialog v-model="dialogTableVisible" width="60%" :close-on-click-modal="false" append-to-body destroy-on-close
      :title="dialogTitle">
      <el-form ref="eventFormRef" :model="eventForm" label-width="120px" class="demo-eventForm" size="default"
        label-position="top">
        <el-form-item label="事件描述" prop="describe" :rules="[
          { required: true, message: '请输入事件描述', trigger: 'blur' },
        ]">
          <el-input v-model.trim="eventForm.describe" />
        </el-form-item>

        <el-form-item label="事件类型" prop="type" :rules="[
          { required: true, message: '请选择事件类型', trigger: 'change' },
        ]">
          <el-select v-model="eventForm.type" placeholder="请选择事件类型" @change="eventChange">
            <el-option key="1" label="弹框" value="dialog" />
            <el-option key="2" label="提示" value="message" />
            <el-option key="3" label="自定义" value="custom" />
          </el-select>
        </el-form-item>

        <!-- 消息配置 -->
        <template v-if="eventForm.type == 'message'">
          <el-form-item label="消息类型" prop="options.messageType" :rules="[
            { required: true, message: '请选择事件类型', trigger: 'change' },
          ]">
            <el-radio-group v-model="eventForm.options.messageType" @change="messageSetting">
              <el-radio label="success">成功</el-radio>
              <el-radio label="warning">警告</el-radio>
              <el-radio label="error">错误</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="消息内容" prop="options.messageDescribe"
            :rules="[{ required: true, message: '消息内容', trigger: 'blur' }]">
            <el-input v-model.trim="eventForm.options.messageDescribe" @change="messageSetting" />
          </el-form-item>
        </template>

        <!-- 弹框配置 -->
        <template v-if="eventForm.type == 'dialog'">
          <el-form-item label="打开弹框" prop="options.dialogName" :rules="[
            { required: true, message: '请选择弹框', trigger: 'change' },
          ]">
            <el-select v-model="eventForm.options.dialogName" placeholder="请选择弹框" @change="dialogSetting">
              <el-option v-for="(dialog, index) in dialogOptions" :key="index" :label="dialog.label"
                :value="dialog.value">
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <func-wrap v-show="eventForm.type == 'custom'">
          <low-code-editor ref="editorRef" :mode="'javascript'" :readonly="false" v-model="editorCode"></low-code-editor>
        </func-wrap>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, watch, computed } from "vue";
import { lowCode, Component } from "@/components/low-code/core/index";
import { ElMessage } from "element-plus";
import funcWrap from "@/components/low-code/page-designer/components/func-wrap/index.vue";

export default defineComponent({
  components: { funcWrap },
  setup() {
    const dialogTableVisible = ref(false);
    const eventFormRef = ref() as any;
    const eventForm = reactive({
      name: "",
      type: "",
      describe: "",
      options: {
        messageType: "",
        messageDescribe: "",
        dialogName: "",
      },
    });
    const dialogTitle = ref("新建事件");

    const editorRef = ref();
    const editorCode = ref(``);
    const currentEditor = ref<{
      code: string;
      describe: string;
      options?: any;
      func: string;
    } | null>(null);
    const addEvent = () => {
      dialogTitle.value = "新建事件";
      eventForm.type = "custom";
      editorCode.value = `const { data , $ , axios , ElMessage } = controller;`;
      dialogTableVisible.value = true;
    };
    const editor = (row: {
      code: string;
      type: string;
      describe: string;
      func: string;
      options: any;
    }) => {
      dialogTitle.value = "编辑事件";
      currentEditor.value = row;
      editorCode.value = row.func;
      eventForm.type = row.type;
      eventForm.describe = row.describe;
      eventForm.options = row.options;
      dialogTableVisible.value = true;
    };
    const remove = (row: { code: string }) => {
      lowCode.eventCenterController.removeEvent(row.code);
    };

    const getValues = () => {
      ElMessage.success("保存成功");
    };

    const confirmSave = async () => {
      if (!eventFormRef.value) return;
      await eventFormRef.value.validate((valid: any, fields: any) => {
        if (valid) {
          console.log("submit!");
          try {
            if (dialogTitle.value == "新建事件") {
              lowCode.eventCenterController.addEvent(
                eventForm.type,
                eventForm.describe,
                eventForm.options,
                editorCode.value
              );
              dialogTableVisible.value = false;
              return false;
            }
            if (currentEditor.value) {
              lowCode.eventCenterController.editorEvent(
                eventForm.type,
                currentEditor.value?.code,
                eventForm.options,
                eventForm.describe,
                editorCode.value
              );
              dialogTableVisible.value = false;
            }
          } catch (error) { }
        } else {
          console.log("error submit!", fields);
        }
      });
    };

    watch(dialogTableVisible, (newDialogTableVisible) => {
      if (!newDialogTableVisible) {
        editorCode.value = "";
      }
    });

    const dialogOptions = computed(() => {
      let options: any[] = Object.values(lowCode.dataCenter)
        .filter((component) => {
          return component.type == "dialog";
        })
        .map((component) => ({
          label: (<Component>component).selector,
          value: (<Component>component).selector,
        }));
      console.log("options", options);
      return options;
    });

    const eventChange = () => {
      if (eventForm.type == "dialog") {
        editorRef.value.setValue(
          `const { data , $ , axios , ElMessage } = controller;

$("弹框").open();
`
        );
      }
      if (eventForm.type == "message") {
        editorRef.value.setValue(
          `const { data , $ , axios , ElMessage } = controller;

ElMessage.success("保存成功");
`
        );
      }
      if (eventForm.type == "custom") {
        editorRef.value.setValue(
          `const { data , $ , axios , ElMessage } = controller;`
        );
      }
    };

    const messageSetting = () => {
      editorRef.value.setValue(
        `const { data , $ , axios , ElMessage } = controller;

ElMessage.${eventForm.options.messageType}("${eventForm.options.messageDescribe}");
`
      );
    };

    const dialogSetting = () => {
      editorRef.value.setValue(
        `const { data , $ , axios , ElMessage } = controller;

$("${eventForm.options.dialogName}").open();
`
      );
    };

    return {
      lowCode,
      eventFormRef,
      eventForm,
      addEvent,
      editor,
      remove,
      dialogTableVisible,
      editorRef,
      editorCode,
      getValues,
      confirmSave,
      currentEditor,
      dialogTitle,
      eventChange,
      messageSetting,
      dialogSetting,
      dialogOptions,
    };
  },
});
</script>

<style scoped>
.event-center-wrap {
  padding: 20px;
}

.box-card {
  min-height: 300px;
}

.add-event-center {
  float: right;
  padding: 3px 0;
  padding: 3px 8px;
}

.el-select {
  width: 100%;
}
</style>
